package cn.com.ntr.jhclient;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import cn.com.ntr.jhclient.adapter.CityAdapter;
import cn.com.ntr.jhclient.db.DBAllProvince;
import cn.com.ntr.jhclient.db.DatabaseFactory;
import cn.com.ntr.jhclient.json.JsonPaserInterf;
import cn.com.ntr.jhclient.model.City;
import cn.com.ntr.jhclient.model.ProvinceCity;
import cn.com.ntr.jhclient.util.Constant;
import cn.com.ntr.jhclient.util.SharePreferenceUtil;
import cn.com.ntr.jhclient.view.CommonDialog;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

public class ChooseAreaActivity extends Activity {
	private Button btnBack;
	private ListView listView;
	private CommonDialog dlg;
	private DBAllProvince dbCity;
	private CityAdapter adapter;
	private List<City> list;
	private static String pid;
	private static final int FINISHED = 2;
	private AsyncHttpClient client = new AsyncHttpClient();
	private JsonPaserInterf jsonParser;
	private static final int SUCCESS = 1;
	private static final int NO_DATA = -1;
	private static final int FAILED = 0;
	private List<ProvinceCity> pList;
	public static void setPid(String _pid) {
		pid = _pid;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_choose_area_1);
		init();
		registerListener();
		dlg.show();
//		boolean hasData=SharePreferenceUtil.getHasDataFlag(this, SharePreferenceUtil.HAS_CITY_DATA);
//		if(hasData){
			queryCity(pid);
//		}else{
//			initDatabase(pid);
//		}
		
	}

	private void init() {
		jsonParser = DatabaseFactory.getJsonPaserInterface();
		btnBack = (Button) findViewById(R.id.btn_back);
		listView = (ListView) findViewById(R.id.listview);
		dlg = new CommonDialog(this, null);
		dlg.setDialogMsg(getString(R.string.data_loading));
		dbCity = new DBAllProvince(this);
		adapter = new CityAdapter(this);
		listView.setAdapter(adapter);
	}

	private void registerListener() {
		btnBack.setOnClickListener(clickListener);
		listView.setOnItemClickListener(itemClick);
	}

	private OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btn_back:
				finish();
				break;
			default:
				break;
			}
		}
	};
	private void initDatabase(final String pid) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				client.get(ChooseAreaActivity.this, Constant.PROVINCE_LIST+"fid/"+pid,
						new JsonHttpResponseHandler() {
							@Override
							public void onSuccess(JSONArray array) {
								// TODO Auto-generated method stub
								if (array != null && array.length() > 0) {
									pList = jsonParser
											.parserAllData(array);
									int size=pList.size();
									if (pList == null ||size == 0) {
										return;
									}
									for (int i = 0; i < size; i++) {
										ProvinceCity all = pList.get(i);
										dbCity.insert(all);
									}
									handler.sendEmptyMessage(SUCCESS);
								} else {
									handler.sendEmptyMessage(NO_DATA);
								}
							}

							@Override
							public void onFailure(Throwable arg0) {
								// TODO Auto-generated method stub
								handler.sendEmptyMessage(FAILED);
							}
						});
			}
		}).start();
		
	}
	private OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			// TODO Auto-generated method stub
			City city = list.get(position);
			Intent data = new Intent(ChooseAreaActivity.this,
					SearchPositionActivity.class);
			data.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			SearchPositionActivity.setMulCityCode(city.getCityId());
			SearchPositionActivity.setMulCityName(city.getCityName());
			startActivity(data);
			overridePendingTransition(R.anim.push_right_in,
					R.anim.push_right_out);
			finish();
		}

	};
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case FINISHED:
				dlg.dismiss();
				Object[] obj = (Object[]) msg.getData().getSerializable("list");
				List<City> list = new ArrayList<City>();
				for (int i = 0; i < obj.length; i++) {
					City city = (City) obj[i];
					list.add(city);
				}
				adapter.addAll(list);
				listView.setAdapter(adapter);
				break;
			case SUCCESS:
				dlg.dismiss();
				SharePreferenceUtil.saveHasDataFlag(getBaseContext(), SharePreferenceUtil.HAS_CITY_DATA, true);
				list=new ArrayList<City>();
				for(ProvinceCity pc:pList){
					City city=new City();
					city.setCityId(pc.getpId());
					city.setCityName(pc.getpName());
					city.setProId(pc.getfId());
					list.add(city);
				}
				adapter.addAll(list);
				listView.setAdapter(adapter);
				break;
			case FAILED:
				dlg.dismiss();
				break;
			case NO_DATA:
				dlg.dismiss();
				break;
			default:
				break;
			}
		}

	};

	private void queryCity(final String pid) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				list = dbCity.queryCity(pid);
				Message msg = new Message();
				msg.what = FINISHED;
				msg.getData().putSerializable("list", list.toArray());
				handler.sendMessage(msg);
			}
		}).start();
	}
}
